package com.gupaoedu.vip;

import java.io.*;
import java.net.Socket;

/**
 * <p>
 *
 * </p>
 *
 * @author Nicky
 * @since 2019-10-05
 */
public class RpcNetTransport {

  private String host;

  private int port;

  public RpcNetTransport(String host, int port) {
    this.host = host;
    this.port = port;
  }

  public Object send(RpcRequest rpcRequest){

    Socket socket = null;
    Object result = null;
    ObjectOutputStream objectOutputStream = null;
    ObjectInputStream objectInputStream = null;

    try {
      socket = new Socket(host,port);
      objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
      objectOutputStream.writeObject(rpcRequest);

      objectInputStream = new ObjectInputStream(socket.getInputStream());
      result = objectInputStream.readObject();

    } catch (IOException e) {
      e.printStackTrace();
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
    }
    finally {
      if(objectInputStream !=null){
        try {
          objectInputStream.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
      if(objectOutputStream != null){
        try {
          objectOutputStream.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }

    return result;


  }
}
